<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\Request;
use think\Db;

/**
 * 标签管理
 */
class Label extends AdminBase {

    //定义数据表
    private $db;

    public function __construct() {
        parent::__construct();
        $this->db = Db::name('Label');
    }

    //标签列表
    public function index() {
        $where = 1;
        if($label_name = input('get.label_name'))
            $where .= ' and label_name like "%'.$label_name.'%"';
        
        //获取标签列表
        $data = $this->db->where($where)->order('id desc')->paginate(10,false,['query'=>['label_name'=>input('param.label_name')]]);
        // 获取分页显示
        $page = $data->render();
        // 模板变量赋值
        $this->assign('data', $data->all());
        $this->assign('page', $page);
        return $this->fetch();
    }

    //添加标签
    public function add() {
        if (Request::instance()->isPost()) {
            $data = input('post.'); 
            $result = $this->validate($data,'label.add');

            if(true  !== $result){
                $this->error($result);
            }else{
                $data['label_fist'] = ucfirst(substr($data['pingying'], 0,1));
                $this->db->insert($data);
                $this->success('标签添加成功');
            }	
        } else {
            return $this->fetch();
        }
    }

    // 修改标签
    public function edit() {
        if (Request::instance()->isPost()) {
            $data = input('post.'); 
            $result = $this->validate($data,'label.edit');

            if(true  !== $result){
                $this->error($result);
            }else{
                $data['label_fist'] = ucfirst(substr($data['pingying'], 0,1));
                $this->db->update($data);
                $this->success('标签修改成功');
            }		
        } else {
            $id = Request::instance()->param('id');
            $data = $this->db->where(array('id' => $id))->find();
            $this->assign('data', $data);
            return $this->fetch();
        }
    }

    //删除标签
    public function delete($id = 0, $ids = []) {
        $id = $ids ? $ids : Request::instance()->param('id');
        if($id){
            if (is_numeric($id)) {
                $this->db->delete($id);
            }else{
                $this->db->delete(implode(',',$id));
            }
            $this->delLabelArticle($id);
            $this->success('删除成功');
        }
        $this->error('请选择需要删除的文章');
    }
    
    //删除中间表使用该标签的记录
    protected function delLabelArticle ($label_id) {
         if(is_numeric($label_id)){
            //删除绑定的标签
            Db::name('ArticleLabel')->where(['label_id'=>$label_id])->delete();
        }else{
            //删除绑定的标签
            Db::name('ArticleLabel')->where(['label_id'=>['in',implode(',',$label_id)]])->delete();
        }
    }
}
